package com.runfast.waimai.utils.websocket;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.runfast.paotui.dao.model.Order;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.WaiMaiRunfastAgentaccountsService;
import com.runfast.waimai.service.WaiMaiRunfastAgentbusinessService;
import com.runfast.waimai.web.controller.shopper.ShopperController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 功能说明：websocket处理类, 使用J2EE7的标准
 * @version 1.0
 */
@Component
@ServerEndpoint("/websocket/diaodu/{userName}/{userType}/{token}")
public class DiaoDuWebsocketController {
    @Autowired
    private WaiMaiRunfastAgentbusinessService runfastAgentbusinessService;
    @Autowired
    private WaiMaiRunfastAgentaccountsService runfastAgentaccountsService;
    @Autowired
    private ShopperController shopperController;
	private static final Logger logger = LoggerFactory.getLogger(DiaoDuWebsocketController.class);

    private Session session;

    public static CopyOnWriteArraySet<DiaoDuWebsocketController> webSockets = new CopyOnWriteArraySet<>();
    //public static Map<String, Session> clients = new ConcurrentHashMap<String, Session>();
    public static Map<String, Map> userSession = new ConcurrentHashMap<String, Map>();
    /**
     * 打开连接时触发
     * @param //myWebsocket
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userName")String userName, @PathParam("userType")String userType, @PathParam("token")String token){
        Map<String,String> map=new HashMap<>();
        map.put("userName",userName);
        map.put("userType",userType);
        userSession.put(session.getId(),map);
        this.session = session;
        webSockets.add(this);
        System.out.println("1---------------------------------------------------------------------------------------------------------------------------------------------------------------");
    }

    /**
     * 收到客户端消息时触发
     * @param myWebsocket
     * @param message
     * @return
     */
    @OnMessage
    public String onMessage(@PathParam("myWebsocket") String myWebsocket, String message) {
        System.out.println("2");
        return "Got your message ("+ message +").Thanks !";
    }

    /**
     * 异常时触发
     * @param myWebsocket
     * @param throwable
     */
    @OnError
    public void onError(@PathParam("myWebsocket") String myWebsocket, Throwable throwable) {
        System.out.println("3");
        webSockets.remove(this);
    }

    /**
     * 关闭连接时触发
     * @param //myWebsocket
     */
    @OnClose
    public void onClose() {
        System.out.println("4------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
        webSockets.remove(this);
    }


    /**
     * 将数据传回客户端
     * 异步的方式
     * @param //myWebsocket
     * @param //message
     */
    public  void broadcast(RunfastGoodsSellRecord order, WaiMaiRunfastShopper shopper, Order order1) {
        Map<Object,Object> map1=new HashMap<Object, Object>();
        if(order!=null){
             if(order.getIspay()!=null && order.getIspay()==1){
                 if(order.getStatus()!=null && order.getStatus()==9){
                     order.setAbnormal(1);
                 }else if(order.getStatus()!=null && order.getIscancel()!=null && order.getIscancel()==1){
                     order.setAbnormal(1);
                 }else if(order.getStatus()!=null &&  order.getIsrefund()!=null && order.getIsrefund()==0){
                     order.setAbnormal(1);
                 }
                 map1.put("order",order);
             }
        }
        if(shopper!=null){
            List<WaiMaiRunfastShopper> list=new ArrayList<WaiMaiRunfastShopper>();
            list.add(shopper);
            shopperController.setList(list);
            map1.put("shopper",shopper);
        }
        if(order1!=null){
            if(order1.getPaid()!=null && order1.getPaid()==true){
                map1.put("paotuiOrder",order1);
            }
        }
        if(map1.size()>0){
            String message= JSONObject.toJSONStringWithDateFormat(map1,"yyyy-MM-dd HH:mm:ss",SerializerFeature.WriteMapNullValue);
            for (DiaoDuWebsocketController webSocket : webSockets) {
                Map map=userSession.get(webSocket.session.getId());
                if(map.get("userType").equals("2")){
                    WaiMaiRunfastAgentaccounts runfastAgentaccounts=runfastAgentaccountsService.findByaccounts(map.get("userName").toString());
                    //AgentBusiness代理商
                    WaiMaiRunfastAgentbusiness runfastAgentbusiness=runfastAgentbusinessService.selectByPrimaryKey(runfastAgentaccounts.getAgentid());
                    if(runfastAgentbusiness!=null){
                        if((order!=null && order.getAgentid().equals(runfastAgentbusiness.getId()))||(shopper!=null && shopper.getAgentid().equals(runfastAgentbusiness.getId()))){
                            try {
                                webSocket.session.getBasicRemote().sendText(message);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }
}
